package com.dxh.common;

import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Iterator;

import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.MemoryCacheImageInputStream;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGEncodeParam;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
import com.sun.imageio.plugins.bmp.BMPImageReader;
import com.sun.imageio.plugins.gif.GIFImageReader;
import com.sun.imageio.plugins.jpeg.JPEGImageReader;
import com.sun.imageio.plugins.png.PNGImageReader;

public class ImageUtil {
	public static final String TYPE_GIF = "image/gif";
	public static final String TYPE_JPEG = "image/jpeg";
	public static final String TYPE_PNG = "image/png";
	public static final String TYPE_BMP = "image/bmp";
	public static final String TYPE_NOT_AVAILABLE = "na";

	private static Log _log = LogFactory.getLog(ImageUtil.class);

	/**
	 * 获取图片文件类型
	 * @param textObj
	 * @return
	 */
	public static String getImageType(byte[] textObj) {
		String type = TYPE_NOT_AVAILABLE;
		ByteArrayInputStream bais = null;
		MemoryCacheImageInputStream mcis = null;
		try {
			bais = new ByteArrayInputStream(textObj);
			mcis = new MemoryCacheImageInputStream(bais);
			Iterator<ImageReader> itr = ImageIO.getImageReaders(mcis);
			while (itr.hasNext()) {
				ImageReader reader = itr.next();
				if (reader instanceof GIFImageReader) {
					type = TYPE_GIF;
				} else if (reader instanceof JPEGImageReader) {
					type = TYPE_JPEG;
				} else if (reader instanceof PNGImageReader) {
					type = TYPE_PNG;
				} else if (reader instanceof BMPImageReader) {
					type = TYPE_BMP;
				}
				reader.dispose();
			}
		} finally {
			if (bais != null) {
				try {
					bais.close();
				} catch (IOException ioe) {
					if (_log.isWarnEnabled()) {
						_log.warn(ioe);
					}
				}
			}
			if (mcis != null) {
				try {
					mcis.close();
				} catch (IOException ioe) {
					if (_log.isWarnEnabled()) {
						_log.warn(ioe);
					}
				}
			}
		}
		if (_log.isDebugEnabled()) {
			_log.debug("Detected type " + type);
		}
		return type;
	}

	/**
	 * @param	imagefile			图片文件流
	 * @param resizeTimes		这个参数是要转化成的倍数,如果是1就是转化成1倍  0.8f是80%
	 * @param quality				 压缩质量   值越大  压缩出来的图片所占字节越多 0.3f
	 * @return
	 */
	public static byte[] writeHighQuality(byte[] imagefile,float resizeTimes,float quality){
		byte[] b = null;
		ByteArrayInputStream in = new ByteArrayInputStream(imagefile);    //将byte[]作为输入流
		try {  
			BufferedImage im = ImageIO.read(in);     //将in作为输入流，读取图片存入image中，而这里in可以为ByteArrayInputStream();
      BufferedImage result = null;  
      //原始图像的宽度和高度   
      int width = im.getWidth();  
      int height = im.getHeight();  
      //调整后的图片的宽度和高度   
      int toWidth = (int) (width * resizeTimes);  
      int toHeight = (int) (height * resizeTimes);  
      // 新生成结果图片   
      result = new BufferedImage(toWidth, toHeight,BufferedImage.TYPE_INT_RGB);  
      //绘制新图片
      result.getGraphics().drawImage(im.getScaledInstance(toWidth, toHeight,java.awt.Image.SCALE_SMOOTH), 0, 0, null);  
      JPEGEncodeParam jep = JPEGCodec.getDefaultJPEGEncodeParam(result);  
      jep.setQuality(quality, true);   //压缩质量   
      ByteArrayOutputStream out = new ByteArrayOutputStream();
	    JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);  
	    encoder.encode(result, jep);  //近JPEG编码  
      //获取图片类型
      String imageType = ImageUtil.getImageType(imagefile);
      ImageIO.write(result,imageType,out);
      b = out.toByteArray();
			if(in != null)
					in.close();
			if(out != null)
					out.close();
      return b;
		} catch (Exception e) {
	  	 System.out.println("图片压缩异常："+e.getMessage());
	  	 e.printStackTrace();
	  	 return imagefile;//当异常时将原图返回
	   }
	}
	
}
